import { ref } from 'vue';
import useWdToast from "./useWdToast"
import {
	genTestUserSig,
} from "@/libs/im-debug/index.js";

// #ifdef APP
import CallkitPluginServer from '@/im/libs/im/plugins/extension-server/callkit';
// #endif

import TUIChatEngine, {
	TUIStore,
	StoreName,
	IMessageModel,
	TUIGroupService,
	TUIUserService,
	TUIChatService,
	TUIFriendService,
	IConversationModel,
	TUIConversationService,
} from '@tencentcloud/chat-uikit-engine';


const wdToast = useWdToast();
export const sendMessageErrorCodeMap : Map<number, string> = new Map([
	[3123, '文本包含本地审核拦截词'],
	[4004, '图片消息失败,无效的图片格式'],
	[4005, '文件消息失败,禁止发送违规封禁的文件'],
	[7004, '文件不存在,请检查文件路径是否正确'],
	[7005, '文件大小超出了限制,如果上传文件,最大限制是100MB'],
	[8001, '消息长度超出限制,消息长度不要超过12K'],
	[80001, '消息或者资料中文本存在敏感内容,发送失败'],
	[80004, '消息中图片存在敏感内容,发送失败'],
]);
// 必填信息
const config : any = {
	SDKAppID: 1600035983, // Your SDKAppID
	secretKey: "4d2d882033594899ed47528b62f6b390937975918c114fff057985d9b507f383", // Your secretKey
	userID: "",
};
// 会话列表
// const conversationList = ref<IConversationModel[]>([]);
// 信息列表
// const messageList = ref<IMessageModel[]>([]);
// 是否漫游加载完成
// const isCompleted = ref<boolean>(false)
// 当前会话id
// const currentConversationID = ref("" as string);
// 当前会话信息
// const currentConversation = ref<IConversationModel>(null);
// 是否初始化
// const isInitialized = ref<boolean>(false);
export default function useTencentIm() {
	// 初始化 腾讯信息 im 相关配置信息
	// 获取用户id
	// 生成 登录密文，此处建议后端生成
	// 执行腾讯 im 登录方法
	const login = async (loginConfig) => {
		// config.userID = userId; // User ID
		console.log("loginConfig", loginConfig)
		config.chat_userSig = genTestUserSig(loginConfig).userSig;
		// 向下兼容，新版本在 index.ts 中默认执行 init 操作
		// #ifdef APP
		new CallkitPluginServer();
		// #endif
		TUIChatEngine.setLogLevel(3);
		if (!TUIChatEngine.isReady()) {
			// TUICore login
			// isInitialized.value = true;

			let res = await TUIChatEngine.login({
				SDKAppID: loginConfig.SDKAppID,
				userID: loginConfig.userID,
				// UserSig 是用户登录即时通信 IM 的密码，其本质是对 UserID 等信息加密后得到的密文。
				// 该方法仅适合本地跑通 Demo 和功能调试，详情请参见 https://cloud.tencent.com/document/product/269/32688     
				userSig: config.chat_userSig,
				// 如果您需要发送图片、语音、视频、文件等富媒体消息，请设置为 true
				useUploadPlugin: true,
				// 本地审核可识别、处理不安全、不适宜的内容，为您的产品体验和业务安全保驾护航
				// 此功能为增值服务，请参考：https://cloud.tencent.com/document/product/269/79139
				// 如果您已购买内容审核服务，开启此功能请设置为 true
				useProfanityFilterPlugin: false,
				// #ifdef VUE3
				framework: `vue3` // 当前开发使用框架 vue2 / vue3
				//  #endif
				// #ifdef VUE2
				framework: `vue2` // 当前开发使用框架 vue2 / vue3
				//  #endif
			});

			return res;
			// TUIChatEngine.setLogLevel(3)

		}

	}
	// 销毁
	const destroy = () => {
		return TUIChatEngine.destroy();
	}

	const updateMyProfile = (user ?: any) => {
		return TUIUserService.updateMyProfile({
			nick: user.name,
			avatar: user.head
		});
	}




	// 监听会话列表
	const watchConversa = (watchFun : { [key : string] : Function }) => {
		TUIStore.watch(StoreName.CONV, {
			currentConversationID: (id : string) => {
				if (watchFun && watchFun.currentConversationID) {
					watchFun.currentConversationID(id)
				}
			},
			conversationList: (list : IConversationModel[]) => {
				// conversationList.value = list;
				if (watchFun && watchFun.conversationList) {
					watchFun.conversationList(list)
				}
			},
			totalUnreadCount: (total : any) => {
				// currentConversation.value = conversation;
				if (watchFun && watchFun.totalUnreadCount) {
					watchFun.totalUnreadCount(total)
				}
			},
		});
	}
	const unWatchConversa = () => {
		TUIStore.watch(StoreName.CONV, {
			currentConversationID: () => {
			},
			conversationList: () => {
			},
			currentConversation: () => {
			},
		});
	}
	const unWatchChat = () => {
		TUIStore.unwatch(StoreName.CHAT, {
			messageList: () => {
			},
			messageSource: () => {
			},
			isCompleted: () => {
			},
		});
	}
	// 监听聊天内容列表
	const watchChat = (watchFun : { [key : string] : Function }) => {
		TUIStore.watch(StoreName.CHAT, {
			messageList: (list : IMessageModel[]) => {
				// messageList.value = list;
				if (watchFun && watchFun.messageList) {
					watchFun.messageList(list)
				}
			},
			messageSource: (message : IMessageModel) => {
				if (watchFun && watchFun.messageSource) {
					watchFun.messageSource(message)
				}
			},
			isCompleted: (flag : boolean) => {
				// isCompleted.value = flag;
				if (watchFun && watchFun.isCompleted) {
					watchFun.isCompleted(flag)
				}
			},
		});
	}
	const watchChatNew = (watchFun : { [key : string] : Function }) => {
		TUIStore.watch(StoreName.CHAT, {
			newMessageList: (list) => {
				// isCompleted.value = flag;
				if (watchFun && watchFun.newMessageList) {
					watchFun.newMessageList(list)
				}
			},
		});

	}
	const unWatchFriend = () => {
		TUIStore.unwatch(StoreName.FRIEND, {
			friendApplicationList: (list) => {
			},
			friendApplicationUnreadCount: (list) => {
			},
		})
	}
	const watchFriend = (watchFun : { [key : string] : Function }) => {
		TUIStore.watch(StoreName.FRIEND, {
			friendList: (list) => {
				if (watchFun && watchFun.friendList) {
					watchFun.friendList(list)
				}
			},
			friendApplicationList: (list) => {
				if (watchFun && watchFun.friendApplicationList) {
					watchFun.friendApplicationList(list)
				}
			},
			friendApplicationUnreadCount: (list) => {
				if (watchFun && watchFun.friendApplicationUnreadCount) {
					watchFun.friendApplicationUnreadCount(list)
				}
			},
		})
	}

	const getHistoryMessageList = () => {
		TUIChatService.getMessageList().then(() => {
		});
	}

	const checkFriend = (friendId : string) => {
		return TUIFriendService.checkFriend({
			userIDList: [friendId],
			type: TUIChatEngine.TYPES.SNS_CHECK_TYPE_BOTH
		});
	}
	const createGroup = (groupID : any, name : string, memberList : any[]) => {
		return TUIChatEngine.TUIGroup.createGroup({
			type: TUIChatEngine.TYPES.GRP_WORK,
			groupID,
			name,
			memberList,
			joinOption: TUIChatEngine.TYPES.GRP_JOIN_OPTIONS_NO_VERIFY // 群加入方式，默认为 TUIChatEngine.TYPES.GRP_JOIN_OPTIONS_NO_VERIFY（自由加入）
		});
	}
	const toGroupChat = (groupId : string) => {
		return TUIConversationService.switchConversation(TUIChatEngine.TYPES.CONV_GROUP + groupId)
	}
	const addFriend = (friendId : string) => {
		return TUIFriendService.addFriend({
			to: friendId,
			source: 'AddSource_Type_Web',
			type: TUIChatEngine.TYPES.SNS_ADD_TYPE_BOTH,
		});
	}
	const deleteFriend = (friendId : string) => {
		return TUIFriendService.deleteFriend({
			userIDList: [friendId],
			type: TUIChatEngine.TYPES.SNS_DELETE_TYPE_BOTH
		});
	}
	const updateFriend = (friendId : any, friendCustomField : any) => {
		return TUIFriendService.updateFriend({
			userID: friendId,
			friendCustomField: friendCustomField
		});
	}
	const getFriend = (friendId : any) => {
		try {
			return TUIFriendService.getFriendProfile({
				userIDList: [friendId],
			});
		} catch (error : any) {
			console.log(error)
		}
	}
	const getConversationProfile = async (conversationId : any) => {
		try {
			return await TUIConversationService.getConversationProfile(conversationId);
		} catch (error : any) {
			wdToast.error(sendMessageErrorCodeMap.get(error?.code)
				? sendMessageErrorCodeMap.get(error?.code)
				: error?.message)
		}
	}
	const toFriendChat = async (friendId : string) => {
		return await TUIConversationService.switchConversation(TUIChatEngine.TYPES.CONV_C2C + friendId)
	}
	const switchConversation = (conversationID : string) => {
		// currentConversationID.value = conversationID;
		// 切换会话
		TUIConversationService.switchConversation(conversationID);
	}

	const resendMessage = async (item : any) => {
		try {
			await item.resendMessage();
		} catch (error : any) {
			wdToast.error(sendMessageErrorCodeMap.get(error?.code)
				? sendMessageErrorCodeMap.get(error?.code)
				: error?.message)
		}
	}
	const sendMessage = async (options : any) => {
		try {
			let res = null;
			switch (options.type) {
				case 'text':
					res = await TUIChatService.sendTextMessage(options);
					break;
				case 'image':
					res = await TUIChatService.sendImageMessage(options);
					break;
				case 'video':
					res = await TUIChatService.sendVideoMessage(options);
					break;
				case 'audio':
					res = await TUIChatService.sendAudioMessage(options);
					break;
				case 'custom':
					res = await TUIChatService.sendCustomMessage(options);
					break;
			}
			return res;
		} catch (error : any) {
			wdToast.error(sendMessageErrorCodeMap.get(error?.code)
				? sendMessageErrorCodeMap.get(error?.code)
				: error?.message)
		}
	}

	return {
		...TUIChatEngine,
		StoreName,
		login,
		destroy,
		updateMyProfile,
		watchConversa,
		unWatchConversa,
		watchChat,
		unWatchChat,
		watchFriend,
		unWatchFriend,
		watchChatNew,
		switchConversation,
		toFriendChat,
		getHistoryMessageList,
		resendMessage,
		checkFriend,
		deleteFriend,
		addFriend,
		updateFriend,
		getFriend,
		sendMessage,
		createGroup,
		toGroupChat,
		getConversationProfile,
	};
}